using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using EPiServer.Shell.Gadgets;

using EPiServer.Shell.Web;
using System.ComponentModel.Composition;
using System.Reflection;
using EPiServer.Shell.Resources;
using EPiServer.DataAbstraction;
using EPiServer.Cms.Shell.UI.Models;
using EPiServer.SpecializedProperties;
using EPiServer.Configuration.PageGuide;
using EPiServer.Research.MobileCenter.Models;
using EPiServer.Research.MobileCenter.Core;




namespace EPiServer.Research.MobileCenter.Controllers
{ 
    /// <summary>
    /// Controller for Gadget which selects which gadgets we can see on the MobileCenter 
    /// </summary>
    [Gadget(IconUrl = "Content/mobileicon.png", Name = "MobileSettings", Title = "Mobile Settings", ClientScriptInitMethod = "epi.activateMobileCenter.init", ResourceType = typeof(MobileCenterActivatorController))]
    [ScriptResource("Content/activate-MobileCenter.js")]
    public class MobileCenterActivatorController : Controller
    {
        public ActionResult Index() 
        {
            return View("Index",GetAllGadgets());
        }

        /// <summary>
        /// Takes settings and saves them to the dds
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(List<GadgetSettingsForMobile> settings)
        {
            foreach (GadgetSettingsForMobile gadgets in settings)
            {
                DDSStorage.Instance.Save(gadgets);
            }

            return View("Save");
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetXhtmlProperties(string pagetype)
        {
            PageDefinitionCollection pdc = PageType.Load(pagetype).Definitions;
            var xhtmlproperties = pdc.Where(p => p.Type.Name == "XhtmlString").ToList();
            return Json(xhtmlproperties.Select(p => new { p.Name }));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetStringProperties(string pagetype)
        {
            PageDefinitionCollection pdc = PageType.Load(pagetype).Definitions;
            var stringproperties = pdc.Where(p => p.Type.Name == "String").ToList();
            stringproperties.Add(new PageDefinition { Name = "PageName" });
            stringproperties.Reverse();
            return Json(stringproperties.Select(p => new { p.Name }));
        }

        [AcceptVerbs(HttpVerbs.Get)]
        [GadgetAction(Text = "Settings for page guides")]
        public ActionResult Configure()
        {
            var list = DDSStorage.Instance.GetAllPageGuides();
         
            if (list.Count == 0)
            {
                var username = EPiServer.Security.PrincipalInfo.Current.Name;

                foreach (PageGuideElement pageguide in EPiServer.Configuration.Settings.Instance.Parent.PageGuides)
                {
                    PageGuideModel setting = new PageGuideModel
                    {
                        Name = pageguide.Name,
                        Title = pageguide.Title,
                        IsActive = false,
                        UserName = username
                    };
                    list.Add(setting);
                    DDSStorage.Instance.Save(setting);
                }
            }

            return View("Configure",list);

        }

      /*  [AcceptVerbs(HttpVerbs.Get)]
        [GadgetAction(Text = "Settings for creating pages")]
        public ActionResult Configure()
        {
            var settings = DDSStorage.Instance.LoadSettings();

            var pagetypelist = new List<SelectListItem>();
            PageType tmpPageType = new PageType();

        
            foreach (var item in PageType.List())
            {
                SelectListItem listitem = new SelectListItem();
                if (settings.PageType == item.Name)
                {
                    listitem.Selected = true;
                    tmpPageType = item;
                }
                else
                    if (String.IsNullOrEmpty(settings.PageType) && item.Name.ToLower().Contains("news"))
                    {
                        listitem.Selected = true;
                        tmpPageType = item;
                    }


                listitem.Text = item.Name;
                listitem.Value = item.Name;
                pagetypelist.Add(listitem);
            }
            ViewData["PageTypes"] = pagetypelist;

            if (tmpPageType == null)
            {
                tmpPageType = PageType.List()[0];
            }

            PageDefinitionCollection pdc = tmpPageType.Definitions;

            var xhtmlproperties = pdc.Where(p => p.Type.Name == "XhtmlString").ToList();
            var stringproperties = pdc.Where(p => p.Type.Name == "String").ToList();


            var titlelist = stringproperties.Select(p => new SelectListItem { Selected = (p.Name == settings.PageTitle), Text = p.Name, Value = p.Name }).ToList();
            titlelist.Add(new SelectListItem { Text = "PageName", Value = "PageName", Selected = ("PageName" == settings.PageTitle) });
            ViewData["PageTitle"] = titlelist;

            var maplist = xhtmlproperties.Select(p => new SelectListItem { Selected = (p.Name == settings.MapContent), Text = p.Name, Value = p.Name }).ToList();
            ViewData["MapContent"] = maplist;

            var textlist = xhtmlproperties.Select(p => new SelectListItem { Selected = (p.Name == settings.TextContent), Text = p.Name, Value = p.Name }).ToList();
            ViewData["TextContent"] = textlist;

            var imagelist = xhtmlproperties.Select(p => new SelectListItem { Selected = (p.Name == settings.ImageContent), Text = p.Name, Value = p.Name }).ToList();
            ViewData["ImageContent"] = imagelist;

            return View("Configure", settings);
        }
        */

        [AcceptVerbs(HttpVerbs.Get)]
        [GadgetAction(Text = "Deleting settings")]
        public ActionResult DeleteAll()
        {


            return View("DeleteAll");
        }
       
        [AcceptVerbs(HttpVerbs.Post)]      
        public ActionResult DeleteAll(string emtpy)
        {
            DDSStorage.Instance.DeleteAll();

            return Index();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Configure(IList<PageGuideModel> PageGuide)
        {
            foreach (PageGuideModel pg in PageGuide)
            {
                DDSStorage.Instance.Save(pg);
            }
            return View("Save");
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult XhtmlPropertiesInPagetype(Guid gadgetID, string pagetype)
        {
            var pageType = PageType.Load(pagetype);
            PageDefinitionCollection pdc = pageType.Definitions;

            var xhtmlproperties = pdc.Where(p => p.Type.Name == "XhtmlString").ToList();

            return Json(xhtmlproperties.Select(p => new { p.Name }));

        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult StringPropertiesInPagetype(Guid gadgetID, string pagetype)
        {
            var pageType = PageType.Load(pagetype);
            PageDefinitionCollection pdc = pageType.Definitions;

            var stringproperties = pdc.Where(p => p.Type.Name == "String").ToList();

            return Json(stringproperties.Select(p => new { p.Name }));

        }

   
        [Import]
        public IGadgetFactory GadgetFactory { get; set; }

        /// <summary>
        /// Gets all gadgets as a settingsModel from the DDS
        /// </summary>
        /// <returns>Settings</returns>
        public List<GadgetSettingsForMobile> GetAllGadgets()
        {
           
            var list = DDSStorage.Instance.GetAllGadgets();
            if (list.Count == 0)
            {
                var username = EPiServer.Security.PrincipalInfo.Current.Name;

                foreach (var gadget in GadgetFactory.GetGadgetTemplates())
                {
                    GadgetSettingsForMobile setting = new GadgetSettingsForMobile
                    {
                        Name = gadget.Title,
                        IsActive = false,
                        UserName = username
                    };
                    list.Add(setting);
                    DDSStorage.Instance.Save(setting); 
                }
            }

            return list;
        }

        /// <summary>
        /// Gets the gadget title.
        /// </summary>
        /// <value>The title.</value>
        public static string Title
        {
            get
            {
                return "Mobile Settings";
            }
        }

    }
}
